<?php
if(!defined("DNREAD")) exit();

class userapi{
    var $db;
    var $data =
    array(
    'prefix' => 'punbb_',
    'table' => '',
    'userid' => 'id',
    'forumpath' => 'forum/',
    'cookie'=>'forum_cookie_8c7c20',
    'cookiehost'=>'',
    'cookieexp'=>3600,
    'setting'=>array(),
    'linkreg' => 'forum/register.php',
    'linklost' => 'forum/login.php?action=forget',
    'linkprivmess' => '',
    'linksendmess' => '',
    'linkprofile' => '/forum/profile.php?id='
    );
    var $set =
    array(
    'prefix' => 'all_prefix',
    'forumpath' => 'all_path',
    'cookie'=>'Cookies',
    'cookiehost'=>'Cookies domaine',
    'cookieexp'=>'cookies_expire',
    'linkreg' => 'registr',
    'linklost' => 'rest_pass',
    //'linkprivmess' => 'private_message',
    //'linksendmess' => 'link_send_mess',
    'linkprofile' => 'your_profile'
    );
    var $usermain =
    array(
    'logged' => 0,
    'userid' => 0,
    'gid' => 0,
    'uname' => '',
    'umail' => '',
    'regdate' => '',
    'lastvisit' => '',
    'icq' => '',
    'msn' => '',
    'www' => '',
    'newmsg' => 0,
    'newmsgnr' => 0,
    'avatar' => ''
    );
    var $userfilter =
    array(
    'login' => array('username','login','input'),
    'register' => array('registered','registr_date','date'),
    'visit' => array('last_visit','last_visit','date'),
    'email' => array('email','E-Mail','input'),
    );
    var $groups =
    array();

    function userapi(&$db,$logged = false)
    {
        global $setting,$conf,$group;
        $this->db = &$db;
        if (isset($setting['datainteg']) && !empty($setting['datainteg']) || isset($conf['datainteg']) && !empty($conf['datainteg'])) {
             $data = (isset($conf['datainteg']) && !empty($conf['datainteg'])) ? @unserialize($conf['datainteg']) : @unserialize($setting['datainteg']);
             $n = '';
             foreach ($this->data as $k => $v) {
             	$n[$k] = (isset($data[$k])) ? $data[$k] : $v;
             }
             if(is_array($n)){
                 $this->data = $n;
             }
        }
        if (is_array($group)) {
            foreach ($group as $k => $v){
                if ($v['fid'] > 0) {
                    $this->groups[$v['fid']] = array('gid'=>$v['gid'],'title'=>$v['title']);
                }
           }
        }
        $this->data['table'] = $this->data['prefix'].'users';
        if ($logged) {
            return $this->userarray();
        }
    }

    function avatar($scr, $link = false)
    {
    }

    function userarray()
    {
        global $group;
        if (isset($_COOKIE[$this->data['cookie']])) {
            $pun['userid'] = 1;
            $pun['password'] = 'Guest';
            $pun['expiration_time'] = 0;
            $pun['password_hash'] = $pun['expire_hash'] = '';
            $data = explode('|', base64_decode($_COOKIE[$this->data['cookie']]));
            if (!empty($data) && count($data) == 4) {
			    list($pun['userid'],$pun['password_hash'],$pun['expiration_time'],$pun['expire_hash']) = $data;
	        }
	        $pun['userid'] = intval($pun['userid']);
            if ($pun['userid'] > 1 &&  intval($pun['expiration_time']) > NEWTIME) {
                $newuser = $this->db->fetchrow($this->db->query("SELECT * FROM ".$this->data['prefix']."users WHERE id='".$pun['userid']."' LIMIT 1"));
                if ($pun['userid'] > 1 && $pun['password_hash'] == $newuser['password']) {
                    $newban = $this->db->fetchrow($this->db->query("SELECT id FROM ".$this->data['prefix']."bans WHERE username='".$this->db->escape($newuser['username'])."' LIMIT 1"));
                    if (intval($newban['id']) == 0) {
                        $gid = (isset($this->groups[$newuser['group_id']]['gid']) && intval($this->groups[$newuser['group_id']]['gid']) > 0) ? $this->groups[$newuser['group_id']]['gid'] : 0;
                        $this->usermain = array
                        (
                        'logged'=>1,
                        'userid'=>intval($newuser['id']),
                        'gid'=>$gid,
                        'uname'=>$newuser['username'],
                        'umail'=>$newuser['email'],
                        'regdate'=>$newuser['registered'],
                        'lastvisit'=>$newuser['last_visit'],
                        'icq'=>$newuser['icq'],
                        'msn'=>$newuser['msn'],
                        'www'=>$newuser['url'],
                        'newmsg'=>'',
                        'newmsgnr'=>'',
                        'avatar'=>''
                        );
                    }
                }
            }
        }
    }

    function logout()
    {
        if ($this->usermain['logged'] == 1 && intval($this->usermain['userid']) > 0) {
           setcookie($this->data['cookie'],'',NEWTIME - $this->data['cookieexp'],'/',$this->data['cookiehost']);
           //setcookie($this->data['cookie'],'');
        }
    }

    function forum_hash($str, $salt)
    {
	     return sha1($salt.sha1($str));
    }

    function checkpwd($passw)
    {
        return (strlen($passw) > 32) ? 0 : 1;
    }

    function checklogin($login)
    {
        return (strlen($login) > 32 || strlen($login) < 3) ? 0 : 1;
    }

    function issetmail($mail)
    {
        return $this->db->numrows($this->db->query("SELECT id FROM ".$this->data['prefix']."users WHERE email = '".$this->db->escape($mail)."' AND id <> ".$this->usermain['userid'].""));
    }

    function addmail($mail)
    {
        $this->db->query("UPDATE ".$this->data['prefix']."users SET email = '".$this->db->escape($mail)."' WHERE id = ".$this->usermain['userid']."");
    }

    function addurl($url)
    {
        if ($url) {
            $url = (!preg_match('#^http[s]?:\/\/#i',$url)) ? "http://".$url : $url;
            $url = (!preg_match('#^http[s]?\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i',$url)) ? '' : $url;
        } else {
            $url = '';
        }
        return $url;
    }

    function adduse($icq, $www, $msn)
    {
        //$this->db->query("UPDATE ".$this->data['prefix']."members SET icq = '".$this->db->escape($icq)."', website_url = '".$this->db->escape($www)."',msn = '".$this->db->escape($msn)."' WHERE id_member = '".$this->usermain['userid']."'");
    }

    function associat($in = false)
    {
        $associat = array();
        if ($in) {
            $inq = $this->db->query("SELECT id,username,email,url,icq,registered FROM ".$this->data['prefix']."users WHERE id IN (".$this->db->escape($in).")");
            while ($item = $this->db->fetchrow($inq)) {
                $associat[$item['id']] = array
                (
                'userid' => $item['id'],
                'uname' => $item['username'],
                'regdate' => $item['registered'],
                'avatar' => '',
                'icq' => $item['icq'],
                'www' => $item['url']
                );
            }
        }
        return $associat;
    }

    function login($login, $pass)
    {
        if ($this->usermain['logged'] == 0 && intval($this->usermain['userid']) == 0) {
            $newuser = $this->db->fetchrow($this->db->query("SELECT * FROM ".$this->data['prefix']."users WHERE username = '".$this->db->escape($login)."'"));
            $newban = $this->db->fetchrow($this->db->query("SELECT id FROM ".$this->data['prefix']."bans WHERE username = '".$this->db->escape($newuser['username'])."' LIMIT 1"));
            if (intval($newban['id']) > 0) {
                define('THIS_BANNED',1);
            }
            $hash = $this->forum_hash($pass,$newuser['salt']);
            if (intval($newuser['id']) > 1 && intval($newban['id']) == 0 && $hash == $newuser['password']) {            	$expire = NEWTIME + $this->data['cookieexp'];
            	$printcookie = base64_encode($newuser['id'].'|'.$hash.'|'.$expire.'|'.sha1($newuser['salt'].$hash.$this->forum_hash($expire,$newuser['salt'])));
                setcookie($this->data['cookie'], $printcookie, NEWTIME + $this->data['cookieexp'],'/',$this->data['cookiehost']);
                $gid = (isset($this->groups[$newuser['group_id']]['gid']) && intval($this->groups[$newuser['group_id']]['gid']) > 0) ? $this->groups[$newuser['group_id']]['gid'] : 0;
                $this->usermain = array
                (
                'logged'=>1,
                'userid'=>intval($newuser['id']),
                'gid'=>$gid,
                'uname'=>$newuser['username'],
                'umail'=>$newuser['email'],
                'regdate'=>$newuser['registered'],
                'lastvisit'=>$newuser['last_visit'],
                'icq'=>$newuser['icq'],
                'msn'=>$newuser['msn'],
                'www'=>$newuser['url'],
                'newmsg'=>'',
                'newmsgnr'=>'',
                'avatar'=>''
                );
            }
        }
    }

    function group()
    {
        $associat = array();
        $inq = $this->db->query("SELECT * FROM ".$this->data['prefix']."groups");
        while ($item = $this->db->fetchrow($inq)) {
             $associat[$item['g_id']] = $item['g_title'];
        }
        return $associat;
    }

    function userlist($sf, $nu, $p, $sess, $sql)
    {
        global $lang;
        $inq = $this->db->query("SELECT u.*,b.id AS blocked FROM ".$this->data['prefix']."users AS u LEFT JOIN ".$this->data['prefix']."bans AS b ON b.username = u.username ".str_replace('email','u.email',$sql)." ORDER BY u.id DESC LIMIT $sf,$nu");
        while ($item = $this->db->fetchrow($inq)) {
            $style = (intval($item['blocked']) > 0) ? 'noactive' : 'work-lite';
            if ($item['id'] > 1) {
            echo '<tr>'
                 .'<td class="'.$style.' center">'
                 .$item['username']
                 .'</td>'
                 .'<td class="'.$style.' center">'
                 .format_time($item['registered'],0)
                 .'</td>'
                 .'<td class="'.$style.' center">'
                 .format_time($item['last_visit'],1)
                 .'</td>'
                 .'<td class="'.$style.' center">'
                 .'<a href=mailto:'.$item['email'].'>'.$item['email'].'</a>'
                 .'</td>'
                 .'<td class="'.$style.' center">';
                 //if (intval($item['id_ban']) > 0) {
                 //    echo '<a href="user.php?dn=unban&uid='.$item['id_member'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['ban_del'].'" src="template/'.$sess['skin'].'/images/unblock.gif" border="0"></a>';
                 //} else {
                     //echo '<a href="user.php?dn=ban&uid='.$item['id_member'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['ban_add'].'" src="template/'.$sess['skin'].'/images/block.gif"></a>'
                       echo '<a href="user.php?dn=edit&uid='.$item['id'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['all_edit'].'" src="template/'.$sess['skin'].'/images/edit.gif"></a>';
                         // .'<a href="user.php?dn=del&uid='.$item['user_id'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['all_delet'].'" src="template/'.$sess['skin'].'/images/del.gif"></a>';
                 //}
            }
            echo '</td>'
                 .'</tr>';
        }
    }

   function userdel($uid)
   {
      //if($uid > 2){
      //    $this->db->query("DELETE FROM ".$this->data['prefix']."users WHERE user_id='$uid'");
      //}
   }

   function bandel($uid)
   {
       //if ($uid > 0) {
       //    $this->db->query("DELETE FROM ".$this->data['prefix']."ban_items WHERE id_member = '$uid'");
       //}
   }

   function banadd($uid)
   {
       //if ($uid > 0) {
       //    if ($this->db->numrows($this->db->query("SELECT ban_id FROM ".$this->data['prefix']."banlist WHERE ban_userid='$uid'")) == 0) {
       //        $this->db->query("INSERT INTO ".$this->data['prefix']."banlist VALUES (NULL,$uid,'',NULL)");
       //    }
       //}
   }

   function useredit($uid)
   {
       global $lang;
       if ($uid > 0) {
           $item = $this->db->fetchrow($this->db->query("SELECT * FROM ".$this->data['prefix']."users WHERE id = '".$uid."'"));
           echo '<table  cellpadding="1" cellspacing="1" class="work">'
                .'<tr><td class="work-title center" colspan="2">'.$lang['edit_user'].' '.$item['username'].'</td></tr>'
                .'<tr><td class="work-clip strong center" width="20%">E-Mail :'
                .'</td>'
                .'<td class="work-lite" width="80%">'
                .'<input name="edit[mail]" size="50" maxlength="50" type="text" value="'.$item['email'].'"> '
                .'</td></tr>';

       }
   }

   function usersave($uid, $edit)
   {
      if ($uid > 0 && is_array($edit)) {
          if (isset($edit['mail']) && !empty($edit['mail']) && $this->db->numrows($this->db->query("SELECT id FROM ".$this->data['prefix']."users WHERE email = '".$this->db->escape($edit['mail'])."' AND id <> $uid")) == 0) {
              $this->db->query("UPDATE ".$this->data['prefix']."users SET email = '".$this->db->escape($edit['mail'])."' WHERE id = '$uid'");
          }

      }
   }

  function messagelast($bs)
  {
      global $api,$lang;
      $re = '';
      $bs['order'] = (isset($bs['order']) && $bs['order'] == 'desc') ? 'desc' : 'asc';
      $inq = $this->db->query("SELECT a.id,a.subject,a.last_post,a.last_poster,a.num_replies,b.id FROM
      ".$this->data['prefix']."topics a LEFT JOIN ".$this->data['prefix']."users b ON b.username = a.last_poster
      ORDER BY a.last_post ".$bs['order']." LIMIT 0,".$bs['col']);
      if ($this->db->numrows($inq) > 0) {
          $target = (empty($bs['target'])) ? '' : ' target="'.$bs['target'].'"';
          $re.= '<table class="forum" width="100%" cellspacing="0" cellpadding="0">'
                .'<tbody class="forumbody">'
                .'<tr>'
                .'<td class="forumtitle">'.$lang['subject'].'</td>';
          if ($bs['author'] == 'yes') {
              $re.= '<td class="forumtitle">'.$lang['author'].'</td>';
          }
          if ($bs['date'] == 'yes') {
              $re.= '<td class="forumtitle">'.$lang['all_data'].'</td>';
          }
          if ($bs['replie'] == 'yes') {
              $re.= '<td class="forumtitle">'.$lang['comment_total'].'</td>';
          }
          $re.= '</tr>'
                .'</tbody>';
          while ($item = $this->db->fetchrow($inq)) {
              $re.= '<tr>'
                    .'<td class="forumtopic">'
                    .'<a href="/forum/viewtopic.php?id='.$item[0].'&action=new">'.$item['subject'].'</a>'
                    .'</td>';
              if ($bs['author'] == 'yes') {
                  $re.= '<td class="forumtopic">'
                        .$item['last_poster']
                        .'</td>';
              }
              if ($bs['date'] == 'yes') {
                  $re.= '<td class="forumtopic">'
                        .'<span class="time">'.$api->sitetime($item['last_post']).'</span>'
                        .'</td>';
              }
              if ($bs['replie'] == 'yes') {
                  $re.= '<td class="forumtopic">'
                    .'<span class="time">'.$item['num_replies'].'</span>'
                    .'</td>';
              }
              $re.= '</tr>';
          }
          $re.= '</table>';
      }
      return $re;
  }
}
?>